package cn.flant.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

public class CglibHelper {

	public static Class<?> generateProxyClass(Class<?> superClass, Class<?>[] interfaces, MethodInterceptor interceptor) {
		Enhancer enhancer = new Enhancer();
		if (superClass != null) {
			enhancer.setSuperclass(superClass);
		}
		if (interfaces != null && interfaces.length > 0) {
			enhancer.setInterfaces(interfaces);
		}
		enhancer.setCallback(interceptor);
		return enhancer.createClass();
	}

	public static Object newProxyInstance(Class<?> superClass, Class<?>[] interfaces, MethodInterceptor interceptor, Class<?>[] argTypes, Object[] args) {
		Enhancer enhancer = new Enhancer();
		if (superClass != null) {
			enhancer.setSuperclass(superClass);
		}
		if (interfaces != null && interfaces.length > 0) {
			enhancer.setInterfaces(interfaces);
		}
		enhancer.setCallback(interceptor);
		if (argTypes != null && args != null) {
			return enhancer.create(argTypes, args);
		} else {
			return enhancer.create();
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T newProxyInstance(Class<T> superClass, MethodInterceptor interceptor, Class<?>[] argTypes, Object[] args) {
		return (T) newProxyInstance(superClass, null, interceptor, argTypes, args);
	}

	@SuppressWarnings("unchecked")
	public static <T> T newProxyInstance(Class<T> superClass, MethodInterceptor interceptor) {
		return (T) newProxyInstance(superClass, null, interceptor);
	}

	public static Object newProxyInstance(Class<?> superClass, Class<?>[] interfaces, MethodInterceptor interceptor) {
		return newProxyInstance(superClass, interfaces, interceptor, null, null);
	}

	public static Object newProxyInstance(Class<?>[] interfaces, MethodInterceptor interceptor) {
		return newProxyInstance(null, interfaces, interceptor);
	}
}
